"""
Copyright (c) 2023 - present SKbioinfo
"""

from flask_restful import reqparse,Resource
from flask import request,jsonify
from flask_login import login_required

from apps.NGS_API.ngsLib.db_ngsLib import *
from apps.NGS_API.record.interface_operate_his import parse_reason
from apps.NGS_API.connector.db_common import *
from apps.NGS_API.utils.log_helper import lg
from apps.NGS_API.common.db_table_config import *
from flask_login import current_user
from apps.NGS_API.record.history_util import *
pm = operation_monitor(table_name=ngs_op_log["name"])

class interfacengsLib(Resource):
    @login_required
    def get(self):
        try:
            ngsLibs = {}
            ### receive ngsLib infos from database ###
            ngsLib_base_info = get_ngsLib_info()
            ### collect ngsLib base info ###
            ngsLib_infos = []
            for ngsLib in ngsLib_base_info:
                ngsLib_infos.append({
                    "id": ngsLib[0],
                    "proj_id": ngsLib[1],
                    "lib_id": ngsLib[2],
                    "stc_id": ngsLib[3],
                    "sam_id": ngsLib[4],
                    "seq_id": ngsLib[5],
                    "run_id": ngsLib[6],
                    "lane": ngsLib[7],
                    "barcode1": ngsLib[8],
                    "barcode2":ngsLib[9],
                    "cre_time":ngsLib[10],
                    "op_user": ngsLib[11],
                    "ch_user": ngsLib[12],
                    "md_time":ngsLib[13],
                    "flag": False
                })
            ngsLibs["ngsLib_infos"] = ngsLib_infos
            response=jsonify(ngsLibs)
            response.status_code = 202
            return response
        except Exception as e:
            lg.error(e)

class interfacengsLibID(Resource):
    @login_required
    def delete(self,id):
        try:
            if request.data.decode(encoding='UTF-8',errors='strict') == "-1":
                pass
            else:
                ### SQL: record reason details ###
                reason_details = parse_reason(data=request.json)
                ### SQL: record user operation ###
                record_user_operate(
                    pm = pm,
                    current_user = current_user,
                    record_table = ngs_op_log["name"],
                    resource_table = ngsLib_db["name"],
                    ch_user = current_user,
                    type_name = "delete",
                    cols = '''
                        library_id
                    ''',
                    id = id,
                    reason_details = reason_details
                )
                ### SQL: record query infos ###
                query_sql = '''
                    SELECT 
                        {col} 
                    FROM 
                        {table_name}
                '''.format(
                    col = ngsLib_qc_db["match"]["lib_id"].split("|")[0],
                    table_name = ngsLib_qc_db["name"]
                )
                tmp_result = query_info(query_sql)
                if len(tmp_result) == 0 or tmp_result == None:
                    print("library qc table is empty!")
                else:
                    delete_id = tmp_result[0][0]
                    ### SQL: delete stock infos ###
                    qc_delete_sql = '''DELETE FROM {table_name} WHERE {db_name} = \"{col_value}\"'''.format(
                        table_name =  ngsLib_qc_db["name"],
                        db_name = ngsLib_qc_db["match"]["lib_id"].split("|")[0],
                        col_value = delete_id
                    )
                    ### STEP 1: delete stock infos ###
                    delete_info(qc_delete_sql)
                ### SQL: delete Lib info ###
                delete_sql = "DELETE FROM {table_name} WHERE {db_name} = \"{col_value}\"".format(
                    table_name=ngsLib_db["name"],
                    col_value=id,
                    db_name="id"
                )
                ### STEP 2: outstock samples ###
                delete_info(delete_sql)
                return id
        except Exception as e:
            lg.error(e)
            
    @login_required  
    def post(self,id):
        try:
            ### SQL: record user operation ###
            parser = reqparse.RequestParser()
            parser.add_argument("reason",type=str,help="",required=True)
            parser.add_argument("extra",type=str,help="",required=True)
            args=parser.parse_args()
            ### SQL: record reason details ###
            reason_details = parse_reason(data=args)
            ### SQL: record user operation ###
            record_user_operate(
                pm = pm,
                current_user = current_user,
                record_table = ngs_op_log["name"],
                resource_table = ngsLib_db["name"],
                ch_user = current_user,
                type_name = "delete",
                cols = '''
                    library_id
                ''',
                id = id,
                reason_details = reason_details
            )
            ### SQL: query outstock sample id ###
            query_sql = '''
                SELECT 
                    {col} 
                FROM 
                    {table_name}
            '''.format(
                col = ngsLib_qc_db["match"]["lib_id"].split("|")[0],
                table_name = ngsLib_qc_db["name"]
            )
            tmp_result = query_info(query_sql)
            if len(tmp_result) == 0 or tmp_result == None:
                print("library qc table is empty!")
            else:
                delete_id = tmp_result[0][0]
                ### SQL: delete stock infos ###
                qc_delete_sql = '''DELETE FROM {table_name} WHERE {db_name} = \"{col_value}\"'''.format(
                    table_name =  ngsLib_qc_db["name"],
                    db_name = ngsLib_qc_db["match"]["lib_id"].split("|")[0],
                    col_value = delete_id
                )
                ### STEP 1: delete stock infos ###
                delete_info(qc_delete_sql)
            ### SQL: delete sample ###
            delete_sql = "DELETE FROM {table_name} WHERE {db_name} =\"{col_value}\"".format(
                table_name=ngsLib_db["name"],
                col_value=id,
                db_name="id"
            )
            ### STEP 2: outstock samples ###
            delete_info(delete_sql)
        except Exception as e:
            lg.error(e)
    @login_required   
    def put(self,id):
        try:
            if request.data.decode(encoding='UTF-8',errors='strict') == "-1":
                pass
            else:
                parser = reqparse.RequestParser()
                parser.add_argument('id',type=str,required=True,help="ID输入有误")
                parser.add_argument('proj_id',type=str, required=True,help="proj_ID输入错误")
                parser.add_argument('lib_id',type=str,required=True,help='文库ID验证错误')
                parser.add_argument('stc_id',type=str,required=True,help="存货ID验证有误") 
                parser.add_argument('sam_id',type=str, required=True,help='样本ID验证错误')
                parser.add_argument('seq_id',type=str,required=True,help="测序ID验证错误")
                parser.add_argument('run_id',type=str,required=True,help="run_id验证错误")
                parser.add_argument('lane',type=str,required=True,help="lane号输入有误")
                parser.add_argument('op_user', type=str, required=True,help="质检员ID错误")
                parser.add_argument('ch_user', type=str,required=True,help="审核人ID有误")
                parser.add_argument('op_time',type=str,required=True,help="操作时间有误")
                parser.add_argument('cre_time', type=str,required=True,help="创建时间不能为空")
                parser.add_argument('barcode1',type=str,required=False,help="barcode1验证有误")
                parser.add_argument('barcode2',type=str,required=False,help="barcode2验证有误")
                args=parser.parse_args(strict=True)
                ### SQL: record update operation ###
                record_user_operate(
                    pm = pm,
                    tag = "lib_id",
                    current_user = current_user,
                    record_table = ngs_op_log["name"],
                    resource_table = ngsLib_db["name"],
                    ch_user = current_user,
                    type_name = "put",
                    cols = ngsLib_db["match"],       
                    id = id,
                    later_infos = args,
                    reason_details = ""
                )
                ### SQL: update ngsLib infos ###
                ngsLib_update_sql="""
                    UPDATE {table_name} SET 
                        library_id=\"{lib_id}\",
                        stock_id=\"{stock_id}\",
                        sample_id=\"{sample_id}\",
                        operate_user=\"{op_user}\",
                        check_user=\"{ch_user}\"            
                    WHERE id=\"{id}\"
                """.format(
                    table_name = ngsLib_db["name"],
                    lib_id=args.get("lib_id"),
                    stock_id=args.get("stc_id"),
                    sample_id=args.get("sam_id"),
                    op_user=args.get("op_user"),
                    ch_user=args.get("ch_user"),
                    id=args.get("id")
                )
                update_info(update_sql=ngsLib_update_sql)
                return 202
        except Exception as e:
            lg.error(e)

class interfacengsLibQC(Resource):
    @login_required
    def get(self):
        pass